package com.payment.system.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.enums.SystemConfigCode;
import com.payment.common.type.SMSTemplateType;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.RedisPoolUtil;
import com.payment.common.utils.StringUtils;
import com.payment.system.domain.Acq;
import com.payment.system.domain.CompanyMoneyChang;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.MerchantDay;
import com.payment.system.domain.MerchantIncreaseLimit;
import com.payment.system.domain.MerchantMonth;
import com.payment.system.domain.MerchantWallet;
import com.payment.system.domain.MoneyChange;
import com.payment.system.domain.PaymentOrder;
import com.payment.system.domain.PlanItemNew;
import com.payment.system.domain.PlanNew;
import com.payment.system.domain.SystemConfig;
import com.payment.system.mapper.AcqMapper;
import com.payment.system.mapper.CompanyMoneyChangMapper;
import com.payment.system.mapper.MerchantDayMapper;
import com.payment.system.mapper.MerchantIncreaseLimitMapper;
import com.payment.system.mapper.MerchantMapper;
import com.payment.system.mapper.MerchantMonthMapper;
import com.payment.system.mapper.MerchantWalletMapper;
import com.payment.system.mapper.MoneyChangeMapper;
import com.payment.system.mapper.PaymentOrderMapper;
import com.payment.system.mapper.PlanItemNewMapper;
import com.payment.system.mapper.PlanNewMapper;
import com.payment.system.mapper.SystemConfigMapper;
import com.payment.system.service.ITaskService;
import com.payment.system.util.GuangGuUtil;
import com.payment.system.vo.PaymentOrderVO;

/**
 * 定时任务实现类
 *
 * @author 情绪失控
 */
@Service
public class TaskServiceImpl implements ITaskService {
    private static final org.slf4j.Logger LOGGER4J = LoggerFactory.getLogger(TaskServiceImpl.class);
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerchantDayMapper merchantDayMapper;
    @Autowired
    private MerchantMonthMapper merchantMonthMapper;
    @Autowired
    private PlanItemNewMapper planItemNewMapper;
    @Autowired
    private PlanNewMapper planNewMapper;
    @Autowired
    private MerchantIncreaseLimitMapper merchantIncreaseLimitMapper;
    @Autowired
    private PaymentOrderMapper paymentOrderMapper;
    @Autowired
    private MerchantWalletMapper merchantWalletMapper;
    @Autowired
    private AcqMapper acqMapper;
    @Autowired
    private SystemConfigMapper configMapper;
    @Autowired
    private MoneyChangeMapper moneyChangeMapper;
    @Autowired
    private CompanyMoneyChangMapper companyMoneyChangMapper;

    /**
     * 查询计划
     */
    @Override
    public void zdplanorder() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        Date parse = null;
        try {
            parse = sdf.parse(date);// 结束时间
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        // 当天最初时间
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        Date todayStartDate = todayStart.getTime();
        System.out.println(date + ";" + sdf.format(todayStartDate));
        // 获取到现在时间的待执行的小计划列表
        List<PlanItemNew> planItemlist = planItemNewMapper.selectPlanItemListByTimeAndStatus(todayStartDate, parse);
        // 查询大计划状态
        PlanNew plan = null;
        for (PlanItemNew planItemNew : planItemlist) {
            plan = planNewMapper.selectPlanNewById(planItemNew.getPlanId());
            // 如果大计划不存在，跳过当前执行下一个
            if (plan == null) {
                continue;
            } else {// 如果大计划的状态为暂停失败删除则跳过,0未执行和 1执行中的放入redis中
                if (plan.getStatus().equals(0) || plan.getStatus().equals(1)) {
                    PlanItemNew p1 = new PlanItemNew();
                    p1.setId(planItemNew.getId());
                    p1.setStatus(1);
                    planItemNewMapper.updatePlanItemNew(p1);
                    RedisPoolUtil.lPush("list.planItemId", planItemNew.getId());
                    Integer planStatus = 0;
                    if (planStatus.equals(plan.getStatus())) {
                        PlanNew plan1 = new PlanNew();
                        plan1.setId(plan.getId());
                        plan1.setStatus(1);
                        planNewMapper.updatePlanNew(plan1);
                    }
                }
            }
        }
    }


    /***
     * 执行计划
     */
    @Override
    public void implementationPlan() {
        // 从redis取出待执行计划
        String id = RedisPoolUtil.rPop("list.planItemId");
        // 如果存在计划则执行计划
        if (!StringUtils.isEmpty(id) && !"nil".equals(id)) {
            // 查询当前执行计划详情
            PlanItemNew planItem = planItemNewMapper.selectPlanItemNewById(id);
            // 查询这组计划是否有未执行完成的计划 根据大计划id和组数查询
            List<PlanItemNew> planItemNews = planItemNewMapper.selectGrouProgress(planItem.getPlanId(),
                    planItem.getGroupNumber());
            if (planItemNews.size() > 1) {
                PlanNew p = new PlanNew();
                p.setId(planItem.getPlanId());
                p.setStatus(4);
                planNewMapper.updatePlanNew(p);
                try {
                    String context = "ID:" + p.getId() + "的计划暂停，因为存在执行中带回调的计划。请及时处理！";
                    Map<String, String> map = new HashMap<>(3);
                    SystemConfig config = configMapper
                            .selectSystemConfigByConfigCode(SystemConfigCode.SEND_PHONE.getCode());
                    // 手机号
                    map.put("user_phone", config.getConfigValue());
                    // 发送内容
                    map.put("content", context);
                    // 业务类型 SEND_OUT:发送验证 NOTICE:短信通知
                    map.put("sendType", SMSTemplateType.NOTICE.getCode());
                    JSONObject gg = GuangGuUtil.smsPackage(map);
                    String resCode = gg.getString("res_code");
                    if (("YQB000000").equals(resCode)) {
                        LOGGER4J.info("计划短信通知发送成功！");
                    }
                } catch (Exception e) {
                    LOGGER4J.error("计划短信通知发送失败！", e);
                }
            } else {
                if (planItem.getStatus().equals(1)) {
                    PlanNew p = planNewMapper.selectPlanNewById(planItem.getPlanId());
                    Merchant m = merchantMapper.selectMerchantById(p.getMerchantId());
                    if (planItem.getMoneyType().equals("payment")) {
                        paymentPlan(planItem, m, p);
                    } else {
                        salePlan(planItem, m, p);
                    }
                }
            }

        }

    }

    // 消费
    private void salePlan(PlanItemNew planItem, Merchant m, PlanNew plan) {
        // TODO Auto-generated method stub
        MerchantIncreaseLimit creditCardId = merchantIncreaseLimitMapper.selectByBankAccount(planItem.getCardNumber());
        Acq acq = acqMapper.selectAcqById(planItem.getAcqId());
        List<String> orderidList = planItemNewMapper.selectOrderNoByPlanIdAndGroupAndType(plan.getId(), planItem.getGroupNumber(), planItem.getMoneyType());
        String orderids = "";
        if (orderidList != null && orderidList.size() > 0) {
            for (int i = 0; i < orderidList.size(); i++) {
                if (i == orderidList.size() - 1) {
                    orderids = orderids + orderidList.get(i);
                } else {
                    orderids = orderids + orderidList.get(i) + ",";
                }
            }
        }
        /** 调用三方消费接口 */
        PaymentOrderVO po = new PaymentOrderVO();
        /** 订单信息保存 */
        PaymentOrder order = new PaymentOrder();
        po.setOrderNos(orderids);
        if (plan.getType().equals(5)) {
            if (planItem.getGroupNumber().equals(0)) {
                po.setPaymentType(3);
                // 养卡消费
                order.setOrderType(7);
            } else {
                po.setPaymentType(2);
                // 养卡消费
                order.setOrderType(7);
            }
        } else {
            po.setPaymentType(1);
            // 养卡消费
            order.setOrderType(1);
        }
        // 公司id
        po.setAcqCode(planItem.getAcqCode());
        // 上游用户编号
        if (StringUtils.isNotEmpty(m.getAcqMerchantNo())) {
            po.setUserId(m.getAcqMerchantNo());
        }
        // 订单号
        po.setOrderNo(StringUtils.createNum());
        // 金额
        po.setAmountMoney(planItem.getMoney());
        // 费率
        po.setRate(plan.getRate());
        // 笔数费
        po.setPro(new BigDecimal(plan.getPro()));
        // 卡号
        po.setCreditNumber(planItem.getCardNumber());
        if (StringUtils.isNotEmpty(m.getIdCardNumber())) {
            // 身份证
            po.setIdCardNo(m.getIdCardNumber());
        }
        // 手机号
        po.setMobile(creditCardId.getBankPhone());
        // 信用卡背面后三位
        po.setMccCode(creditCardId.getCvn());
        // 有效期
        po.setExpired(creditCardId.getExpdate());
        // 姓名/银行卡户名
        po.setBankAccountName(m.getMerchantCnName());
        // 交易地区
        po.setRegion(planItem.getRegion());
        // 交易终端ip
        po.setTrxSourceIp(planItem.getIp());
        // 银行卡代码
        po.setBankCode(creditCardId.getBankName());
        // 卡类型1借记卡2贷记卡
        po.setCardType("2");

        String orderId = StringUtils.randomUUID();
        //小计划 订单ID
        planItem.setOrderId(orderId);
        order.setId(orderId);
        order.setIp(planItem.getIp());
        // 订单号
        order.setOrderNo(po.getOrderNo());
        // 通道id
        order.setAcqId(planItem.getAcqId());
        // 渠道编号
        order.setAcqCode(planItem.getAcqCode());
        // 渠道名称
        order.setAcqName(acq.getAcqName());
        // 清分状态默认未清分
        order.setClearingStatus(0);

        // 成本
        BigDecimal costRate = planItem.getMoney()
                .multiply(acq.getCostRate().divide(new BigDecimal(100)).setScale(4, BigDecimal.ROUND_UP));
        // 成本手续费
        order.setCostRateMoney(costRate);
        // 商户本地id
        order.setMerchantId(plan.getMerchantId());
        // 商户名称
        order.setMerchantName(m.getMerchantCnName());
        // 信用卡号
        order.setCreditNumber(creditCardId.getBankAccount());
        // 银行卡名称
        order.setBankName(planItem.getCardName());
        BigDecimal rateMoney = planItem.getMoney().multiply(new BigDecimal(plan.getRate()).divide(new BigDecimal(100)))
                .setScale(2, BigDecimal.ROUND_UP);
        // 手续费金额
        order.setRateMoney(rateMoney);
        // 订单状态 待回调
        order.setOrderStatus(0);
        // 订单创建时间
        order.setCreateTime(new Date());
        // 金额
        order.setAmountMoney(planItem.getMoney());
        // 查询代理商信息
        // 收益
        order.setProfitMoney(rateMoney.subtract(costRate));
        paymentOrderMapper.insertPaymentOrder(order);
        try {
            JSONObject json = GuangGuUtil.payment(po);
            if ("SUCCESS".equals(json.getString("ret_code"))) {
                order.setAcqOrderNo(json.getString("payment_order_no"));
                if ("YQB000000".equals(json.getString("res_code"))) {
                    // 上游订单号
                    order.setAcqOrderNo(json.getString("payment_order_no"));
                    if ("2".equals(json.getString("status"))) {
                        // 处理中
                        planItem.setStatus(1);
                        order.setOrderStatus(0);
                        order.setAcqReturnCode(json.getString("status"));
                        order.setAcqReturnMsg(json.getString("res_msg"));
                        paymentOrderMapper.updatePaymentOrder(order);
                    } else {
                        // 位置状态默认失败
                        planItem.setStatus(2);
                        order.setOrderStatus(2);
                        order.setAcqReturnCode(json.getString("status"));
                        order.setAcqReturnMsg(json.getString("res_msg"));
                        paymentOrderMapper.updatePaymentOrder(order);
                        PlanNew planUp = new PlanNew();
                        planUp.setId(plan.getId());
                        planUp.setStatus(2);
                        planNewMapper.updatePlanNew(planUp);
                        sendMsg(planUp.getId());
                    }
                } else {
                    planItem.setStatus(2);
                    // 失败
                    order.setOrderStatus(2);
                    order.setAcqReturnCode(json.getString("res_code"));
                    order.setAcqReturnMsg(json.getString("res_msg"));
                    paymentOrderMapper.updatePaymentOrder(order);
                    PlanNew planUp = new PlanNew();
                    planUp.setId(plan.getId());
                    planUp.setStatus(2);
                    planNewMapper.updatePlanNew(planUp);
                    sendMsg(planUp.getId());
                }
            } else {
                // 失败
                planItem.setStatus(2);
                order.setOrderStatus(2);
                order.setAcqReturnCode(json.getString("ret_code"));
                order.setAcqReturnMsg("连接上游失败");
                paymentOrderMapper.updatePaymentOrder(order);
                PlanNew planUp = new PlanNew();
                planUp.setId(plan.getId());
                planUp.setStatus(2);
                planNewMapper.updatePlanNew(planUp);
                sendMsg(planUp.getId());
            }
        } catch (Exception e) {
            // 失败 上送json解析失败
            planItem.setStatus(2);
            order.setOrderStatus(2);
            order.setAcqReturnCode("消费上送json解析");
            order.setAcqReturnMsg("消费上送json解析失败");
            paymentOrderMapper.updatePaymentOrder(order);
            LOGGER4J.error("消费计划上送异常{}", e);
            PlanNew planUp = new PlanNew();
            planUp.setId(plan.getId());
            planUp.setStatus(2);
            planNewMapper.updatePlanNew(planUp);
            sendMsg(planUp.getId());
        }
        planItemNewMapper.updatePlanItemNew(planItem);
    }


    // 还款
    private void paymentPlan(PlanItemNew planItem, Merchant m, PlanNew plan) {
        MerchantIncreaseLimit creditCardId = merchantIncreaseLimitMapper.selectByBankAccount(planItem.getCardNumber());
        Acq acq = acqMapper.selectAcqById(planItem.getAcqId());
        List<String> orderidList = planItemNewMapper.selectOrderNoByPlanIdAndGroupAndType(plan.getId(), planItem.getGroupNumber(), planItem.getMoneyType());
        String orderids = "";
        if (orderidList != null && orderidList.size() > 0) {
            for (int i = 0; i < orderidList.size(); i++) {
                if (i == orderidList.size() - 1) {
                    orderids = orderids + orderidList.get(i);
                } else {
                    orderids = orderids + orderidList.get(i) + ",";
                }
            }
        }
        /** 调用三方接口 */
        PaymentOrderVO pa = new PaymentOrderVO();
        /** 订单信息保存 */
        PaymentOrder order = new PaymentOrder();
        pa.setOrderNos(orderids);
        if (plan.getType().equals(5)) {
            //2空卡
            pa.setPaymentType(2);
            //全额还款
            order.setOrderType(8);
        } else {
            //0 无卡 1养卡
            pa.setPaymentType(1);
            // 养卡代付
            order.setOrderType(2);
        }
        // 公司id
        pa.setAcqCode(planItem.getAcqCode());
        // 订单号
        pa.setOrderNo(StringUtils.createNum());
        // 用户id
        pa.setUserId(m.getAcqMerchantNo());
        // 账户名称
        pa.setBankAccountName(m.getMerchantCnName());
        // 银行卡号
        pa.setCreditNumber(planItem.getCardNumber());
        // 银行卡代码
        pa.setBankCode(creditCardId.getBankName());
        // 银行名称
        pa.setBankName(planItem.getCardName());
        // 证件号
        pa.setIdCardNo(creditCardId.getIdCardNumber());
        // 手机号
        pa.setMobile(creditCardId.getBankPhone());
        // 金额  还款金额+笔数费
        pa.setAmountMoney(planItem.getMoney().add(new BigDecimal(plan.getPro())));
        // 笔数费
        pa.setPro(new BigDecimal(plan.getPro()));
        // 费率
        pa.setRate(plan.getRate());
        //个人账户
        pa.setBankType("1");
        //借记卡
        pa.setCardType("2");
        // ip地址
        pa.setTrxSourceIp(planItem.getIp());

        String orderId = StringUtils.randomUUID();
        order.setId(orderId);
        planItem.setOrderId(orderId);
        // 订单号
        order.setOrderNo(pa.getOrderNo());
        // 通道id
        order.setAcqId(planItem.getAcqId());
        // 渠道编号
        order.setAcqCode(planItem.getAcqCode());
        // 渠道名称
        order.setAcqName(acq.getAcqName());
        // 清分状态默认已清分
        order.setClearingStatus(1);

        // 成本手续费
        order.setCostRateMoney(acq.getDrawRate().setScale(2, BigDecimal.ROUND_UP));
        // 商户本地id
        order.setMerchantId(plan.getMerchantId());
        // 商户名称
        order.setMerchantName(m.getMerchantCnName());
        // 信用卡号
        order.setCreditNumber(creditCardId.getBankAccount());
        // 银行卡名称
        order.setBankName(planItem.getCardName());
        // 手续费金额
        order.setRateMoney(new BigDecimal(plan.getPro()).setScale(2, BigDecimal.ROUND_UP));
        // 订单状态 待回调
        order.setOrderStatus(0);
        // 订单创建时间
        order.setCreateTime(new Date());
        // 金额
        order.setAmountMoney(planItem.getMoney());
        // 收益
        order.setProfitMoney(order.getRateMoney().subtract(order.getCostRateMoney()));
        order.setIp(planItem.getIp());
        paymentOrderMapper.insertPaymentOrder(order);
        try {
            JSONObject json = GuangGuUtil.repayment(pa);
            // 判断调用接口是否成功
            if ("SUCCESS".equals(json.getString("ret_code"))) {
                order.setAcqReturnCode(json.getString("status"));
                order.setAcqReturnMsg(json.getString("res_msg"));
                if ("YQB000000".equals(json.getString("res_code"))) {
                    //同步返回没有成功  不是处理中的直接失败
                    if ("2".equals(json.getString("status"))) {
                        // 处理中
                        order.setOrderStatus(0);
                        paymentOrderMapper.updatePaymentOrder(order);
                    } else {
                        planItem.setStatus(2);
                        order.setOrderStatus(2);
                        PlanNew planUp = new PlanNew();
                        planUp.setId(plan.getId());
                        planUp.setStatus(2);
                        planNewMapper.updatePlanNew(planUp);
                        sendMsg(planUp.getId());
                    }
                } else {
                    planItem.setStatus(2);
                    // 失败
                    order.setOrderStatus(2);
                    PlanNew planUp = new PlanNew();
                    planUp.setId(plan.getId());
                    planUp.setStatus(2);
                    planNewMapper.updatePlanNew(planUp);
                    sendMsg(planUp.getId());
                }
            } else {
                // 失败
                planItem.setStatus(2);
                order.setOrderStatus(2);
                order.setAcqReturnCode(json.getString("ret_code"));
                order.setAcqReturnMsg("连接上游失败");
                PlanNew planUp = new PlanNew();
                planUp.setId(plan.getId());
                planUp.setStatus(2);
                planNewMapper.updatePlanNew(planUp);
                sendMsg(planUp.getId());
            }
        } catch (Exception e) {
            LOGGER4J.error("还款异常{}", e);
            order.setOrderStatus(2);
            order.setAcqReturnCode("444");
            order.setAcqReturnMsg("还款异常：" + e.toString());
            PlanNew planUp = new PlanNew();
            planUp.setId(plan.getId());
            planUp.setStatus(2);
            planNewMapper.updatePlanNew(planUp);
            sendMsg(planUp.getId());
        }
        planItemNewMapper.updatePlanItemNew(planItem);
        paymentOrderMapper.updatePaymentOrder(order);
    }

    /**
     * 统计用户数据并重置资金表数据
     */
    @Override
    public void userStatistics(String time1, String time2, boolean isLastDay) {
        List<MerchantWallet> ml = merchantWalletMapper.selectAll();
        for (MerchantWallet merchantWallet : ml) {
            /* 每月最后一天所有月数据重置 */
            if (isLastDay) {
                merchantWallet.setHkMonth(BigDecimal.ZERO);
                merchantWallet.setSkMonth(BigDecimal.ZERO);
                merchantWallet.setProfitMoth(BigDecimal.ZERO);
                merchantWallet.setPypMonth(BigDecimal.ZERO);
            }
            userDayStatistics(time1, time2, merchantWallet);
            merchantWallet.setHkDay(BigDecimal.valueOf(0));
            merchantWallet.setSkDay(BigDecimal.valueOf(0));
            merchantWallet.setProfit(BigDecimal.valueOf(0));
            merchantWallet.setPypDay(BigDecimal.ZERO);
            merchantWalletMapper.updateMerchantWallet(merchantWallet);
        }

    }

    /**
     * 用户每天数据统计
     */
    private void userDayStatistics(String time1, String time2, MerchantWallet merchantWallet) {
        // 查询当天是否已经统计过
        MerchantDay day = merchantDayMapper.selectMerchantDayByIdAndDate(merchantWallet.getMerchantId(), time1, time2);
        if (day != null) {
            // 如已统计删除原对象
            merchantDayMapper.deleteMerchantDayById(day.getId());
        }
        if (day == null) {
            day = new MerchantDay();
        }
        Date date = DateUtils.dateTime("yyyy-MM-dd", time1.substring(0, 10));
        day.setMerchantId(merchantWallet.getMerchantId());
        day.setHkMoney(merchantWallet.getHkDay());
        day.setSkMoney(merchantWallet.getSkDay());
        day.setPypMoney(merchantWallet.getPypDay());
        day.setProfit(merchantWallet.getProfit());
        day.setTime(date);
        merchantDayMapper.insertMerchantDay(day);
        // 查询月数据是否统计过
        MerchantMonth merchantMonth = merchantMonthMapper.selectMerchantMonthByMerchantIdAndTime(merchantWallet.getMerchantId(), time1.substring(0, 7) + "-01");
        if (merchantMonth != null) {// 有当月统计数据累加
            merchantMonth.setHkMoney(merchantMonth.getHkMoney().add(day.getHkMoney()));
            merchantMonth.setSkMoney(merchantMonth.getSkMoney().add(day.getSkMoney()));
            merchantMonth.setProfit(merchantMonth.getProfit().add(day.getProfit()));
            merchantMonth.setPypMoney(merchantMonth.getPypMoney().add(day.getPypMoney()));
            merchantMonthMapper.updateMerchantMonth(merchantMonth);
        } else {// 没有当月统计数据新建
            MerchantMonth month = new MerchantMonth();
            Date date1 = DateUtils.dateTime("yyyy-MM", time1.substring(0, 7));
            month.setMerchantId(merchantWallet.getMerchantId());
            month.setHkMoney(merchantWallet.getHkMonth());
            month.setSkMoney(merchantWallet.getSkMonth());
            month.setProfit(merchantWallet.getProfitMoth());
            month.setPypMoney(merchantWallet.getPypMonth());
            month.setTime(date1);
            merchantMonthMapper.insertMerchantMonth(month);
        }
    }


    @Override
    public void deleteDay(String time) {
        // TODO Auto-generated method stub
        merchantDayMapper.deleteMerchantDayByTime(time);
    }


    @Override
    public void deleteMonth(String time) {
        // TODO Auto-generated method stub
        merchantMonthMapper.deleteMerchantMonthByTime(time);
    }


    private void sendMsg(String planId) {
        // 短信通知
        try {
            String context = "计划ID:" + planId + "的计划失败，因为存在执行中带回调的计划。请及时处理！";
            Map<String, String> map = new HashMap<>(3);
            // 手机号
            String sendPhone = "";
            try {
                sendPhone = RedisPoolUtil.get("sendPhone");
            } catch (Exception e) {
                sendPhone = "nil";
            }
            if (sendPhone == null || "".equals(sendPhone) || "nil".equals(sendPhone)) {
                SystemConfig config = configMapper
                        .selectSystemConfigByConfigCode(SystemConfigCode.SEND_PHONE.getCode());
                try {
                    // 保存到缓存中
                    RedisPoolUtil.setex("sendPhone", config.getConfigValue(), 86400);
                } catch (Exception e) {

                }
                sendPhone = config.getConfigValue();
            }
            map.put("user_phone", sendPhone);
            // 发送内容
            map.put("content", context);
            map.put("sendType", SMSTemplateType.NOTICE.getCode());
            JSONObject gg = GuangGuUtil.smsPackage(map);
            String resCode = gg.getString("res_code");
            if (("YQB000000").equals(resCode)) {
                LOGGER4J.info("【异步回调】计划短信通知发送成功！");
            }
        } catch (Exception e) {
            LOGGER4J.error("【异步回调】计划短信通知发送失败！", e);
        }
    }


    @Override
    public void partner(String time) {
        // TODO Auto-generated method stub
        List<MoneyChange> li = moneyChangeMapper.partnerList(time);
        for (MoneyChange moneyChange : li) {
            BigDecimal hashMoney = BigDecimal.ZERO;
            Merchant mer = merchantMapper.selectMerchantById(moneyChange.getUserId());
            if (mer != null) {
                String parentPhone = mer.getParentPhone();
                while (true) {
                    Merchant parentUser = merchantMapper.selectMerchantByPhone(parentPhone);
                    if (parentUser == null) {
                        if (hashMoney.compareTo(moneyChange.getTrxAmt()) == 0) {
                            CompanyMoneyChang companyMoneyChang = companyMoneyChangMapper
                                    .selectCompanyMoneyChangByOrderId(moneyChange.getPaymentOrderId());
                            companyMoneyChang.setProfitMoney(
                                    companyMoneyChang.getProfitMoney().subtract(moneyChange.getTrxAmt()));
                            companyMoneyChang.setMoney(companyMoneyChang.getMoney().add(moneyChange.getTrxAmt()));
                            companyMoneyChangMapper.updateCompanyMoneyChang(companyMoneyChang);
                        }
                        break;
                    }
                    if (parentUser.getLevel().equals("6") && hashMoney.compareTo(BigDecimal.ZERO) == 0) {
                        hashMoney = moneyChange.getTrxAmt();
                        int numOne = merchantWalletMapper.increaseInRevenue(parentUser.getId(),
                                moneyChange.getTrxAmt());
                        if (numOne > 0) {
                            moneyChange.setStatus("10C");
                            moneyChange.setUserId(parentUser.getId());
                            moneyChange.setCreateTime(new Date());
                            moneyChangeMapper.updateMoneyChange(moneyChange);
                        }
                    }
                    parentPhone = parentUser.getParentPhone();
                }
            }

        }
    }
}
